package il.ac.tau.dbcourse.gui;

import il.ac.tau.dbcourse.db.Album;
import il.ac.tau.dbcourse.db.DBException;
import il.ac.tau.dbcourse.db.Track;
import il.ac.tau.dbcourse.db.reports.ExistingTrack.TrackDetails;
import il.ac.tau.dbcourse.db.reports.IncompleteAlbum.AlbumDetails;
import il.ac.tau.dbcourse.logic.MixAndMatch;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.nebula.widgets.gallery.DefaultGalleryGroupRenderer;
import org.eclipse.nebula.widgets.gallery.DefaultGalleryItemRenderer;
import org.eclipse.nebula.widgets.gallery.Gallery;
import org.eclipse.nebula.widgets.gallery.GalleryItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

public class AlbumResultWidget extends AlbumWidget {	
	Gallery albumTable;
	GalleryItem group;
	
	public Map<Album, Image> updateAlbumsData() {				
		Image image;
		final Map<Album, Image> result = new HashMap<Album, Image>();
		
		for (AlbumDetails albumDetails: albums) {
			Album album = albumDetails.getAlbum();
			image = AlbumArtProvider.getAlbumArt(1,album.getArtist().getName(), album.getTitle());
			result.put(album, image);							 																																						
		}
		
		MainGui.shell.getDisplay().asyncExec(new Runnable() {			
			@Override
			public void run() {
				for (GalleryItem item: group.getItems()) {							
					Album album = (Album)item.getData();	
				
					Image img = result.get(album);
					if (img != null) {
						item.setImage(img);
					}
				}
				
			}
		});
		
		return result;
	}
	public void setAlbumsData(List<AlbumDetails> als){
		albums=als;		
		int i;
	    i=1;	 	    
		for (AlbumDetails detail:albums){			
			String artist = detail.getAlbum().getArtist().getName();
			String title = detail.getAlbum().getTitle();
			boolean skip = false;
			
			for (GalleryItem otherItem: group.getItems()) {
				Album otherAlbum = (Album)otherItem.getData();
				
				if (otherAlbum.getTitle().toLowerCase().equals(title.toLowerCase()) 
						&& otherAlbum.getArtist().getName().toLowerCase().equals(artist.toLowerCase())) {
					skip = true;
				}
			}
			
			if (skip) continue;				
			GalleryItem item = new GalleryItem(group, SWT.NONE);
			Image image;
			image = AlbumArtProvider.getAlbumArt(2,artist, title);
			
			int has = detail.getSongCount() - detail.getMissingCount();			
			String text = artist + " - " + title + " (" + has + "/" + detail.getSongCount() + ")"; 
			
			item.setText(text);
			item.setImage(image);
			item.setData(detail.getAlbum());
						
			i++;
			albumTable.redraw();
			
			System.out.println("!!!");
		}
	}
	
	public AlbumResultWidget(Composite comp,final Table trackTable,final Group trackGroup) {
		albumTable = new Gallery(comp, SWT.V_SCROLL | SWT.MULTI);
		GridData gridData = new GridData(GridData.FILL_BOTH);	    	    	   	   
	    albumTable.setLayoutData(gridData);
	    
		DefaultGalleryGroupRenderer gr = new DefaultGalleryGroupRenderer();		
		gr.setItemHeight(120);
		gr.setItemWidth(220);		
		gr.setMinMargin(10);		
		gr.setAlwaysExpanded(true);
		albumTable.setGroupRenderer(gr);

		group = new GalleryItem(albumTable, SWT.NONE);
		group.setText("Albums");
		group.setExpanded(true);
		
		DefaultGalleryItemRenderer ir = new DefaultGalleryItemRenderer();
		ir.setShowRoundedSelectionCorners(false);
		albumTable.setItemRenderer(ir);

	    albumTable.addListener(SWT.MouseDown, new Listener () {
			public void handleEvent (Event event) {				
				GalleryItem[] selection = albumTable.getSelection();
				if (selection.length == 0) return; // no selection
				
				GalleryItem item = selection[0];
																													
				if (trackTable!=null) trackTable.remove(0,trackTable.getItemCount()-1);
				try {
					Album album = (Album) item.getData();
					currentlySelectedAlbum = album;
					MixAndMatch mixAndMatch=new MixAndMatch();
					List<Track> tl = mixAndMatch.getMissingTracks(album);
					List<TrackDetails> td = mixAndMatch.getExistingTracks(album);
					mixAndMatch.close();
					if (trackTable!=null) addTracksToTrackTable(tl,td,trackTable);
					if (trackGroup!=null) trackGroup.setText("Album is missing "+ tl.size() +" Tracks ");					
				} catch (DBException e) {
					e.printStackTrace();
				}																	
			}
		});
	}
	
	 private void addTracksToTrackTable(List<Track> tl, List<TrackDetails> td,final Table trackTable){
			TableItem row;
			int i;
			i=1;
			Track track;
			int missingTrackInd,availableTrackInd;
			missingTrackInd=0;
			availableTrackInd=0;
			while ((i<=tl.size()+td.size())&&(missingTrackInd+availableTrackInd<tl.size()+td.size())){
				if (trackTable!=null) {
					row = new TableItem(trackTable, SWT.NONE);
					if (missingTrackInd<tl.size()&&i==tl.get(missingTrackInd).getTrackNumber())
					{
						track =tl.get(missingTrackInd);
						missingTrackInd++;
						row.setText(new String[] {
								"" + track.getTrackNumber() ,
								"" + track.getTitle(),
								"" + track.getLengthString(),
								"" + "Missing",
								""
							});
					}
					if (availableTrackInd<td.size()&&i==td.get(availableTrackInd).getTrack().getTrackNumber())
					{
						track =td.get(availableTrackInd).getTrack();
						availableTrackInd++;
						row.setText(new String[] {
								"" + track.getTrackNumber() ,
								"" + track.getTitle(),
								"" + track.getLengthString(),
								"" + "Exists",
								"" + td.get(availableTrackInd-1).getFilePath()
							});
					}
					else
					{
						System.out.println("ror2");
						
					}
					
				}
				i++;	
			}
	 }
}
